from TTS.api import TTS
import sounddevice as sd
import numpy as np

class ChineseTTS:
    def __init__(self):
        self.tts = TTS("tts_models/zh-CN/baker/tacotron2-DDC-GST")
        self.sample_rate = 22050
        self.volume = 1.0  # 默认音量
        
    def set_volume(self, level):
        """设置音量0.0~1.0"""
        self.volume = max(0.0, min(1.0, level))
    
    def speak(self, text, speed=1.0):
        # 生成语音
        wav = self.tts.tts(text, speaker=self.tts.speakers[0])
        
        # 调整音量
        wav = wav * self.volume
        
        # 调整语速
        if speed != 1.0:
            wav = self._change_speed(wav, speed)
        
        # 播放
        sd.play(wav, self.sample_rate)
        sd.wait()
    
    def _change_speed(self, wav, factor):
        """简单语速调整"""
        from scipy import interpolate
        x = np.arange(len(wav))
        f = interpolate.interp1d(x, wav, kind='linear')
        x_new = np.linspace(0, len(wav)-1, int(len(wav)/factor))
        return f(x_new)

# 使用示例
tts = ChineseTTS()
tts.set_volume(0.8)  # 80%音量
tts.speak("正常语速")
tts.speak("慢速播放", speed=0.7)
tts.speak("快速播放", speed=1.5)